package com.zwcl.common.core.utils;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
 * Base64加解密工具
 * Created by kunye on 2019/07/25.
 */
public final class Base64Util {

    private static final Logger logger = LoggerFactory.getLogger(Base64Util.class);

    private static final Base64 base64 = new Base64();


    public static String encode(String plaintext) {
        try {
            return base64.encodeToString(plaintext.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            logger.error("error: ", e);
            throw new RuntimeException(e);
        }
    }

    public static String encodeUrlSafe(String plaintext) {
        try {
            return base64.encodeBase64URLSafeString(plaintext.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            logger.error("error: ", e);
            throw new RuntimeException(e);
        }
    }

    public static String encodeByteArray(byte[] plaintextByteArray) {
        return base64.encodeToString(plaintextByteArray);
    }

    public static String encodeUrlSafeByteArray(byte[] plaintextByteArray) {
        return base64.encodeBase64URLSafeString(plaintextByteArray);
    }

    public static String decode(String ciphertext) {
        try {
            return new String(base64.decode(ciphertext), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("error: ", e);
            throw new RuntimeException(e);
        }
    }

    public static byte[] decodeToByteArray(String ciphertext) {
        return base64.decode(ciphertext);
    }
}
